package com.kakarote.gateway.config;

import com.kakarote.gateway.service.GatewayRouteService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.config.WebFluxConfigurer;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author zhangzhiwei
 * swagger聚合
 */
@Component
@Primary
@AllArgsConstructor
@Slf4j
@ConditionalOnProperty(prefix = "wk.config", name = "enableDoc", havingValue = "true")
public class SwaggerProvider implements SwaggerResourcesProvider, WebFluxConfigurer {
    /**
     * swagger2默认的url后缀
     */
    public static final String API_URI = "/v2/api-docs";

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private GatewayRouteService routeService;

    @Override
    public List<SwaggerResource> get() {
        List<String> services = discoveryClient.getServices();
        Map<String, RouteDefinition> map = routeService.getRouteDefinitionMap();
        return services.stream().filter(route -> {
            RouteDefinition routeDefinition = map.get(route);
            if (routeDefinition != null) {
                return !Objects.equals(GatewayConst.ROUTER_INTERCEPT_OK, routeDefinition.getMetadata().get(GatewayConst.ROUTER_INTERCEPT));
            }
            return false;
        }).map(route -> swaggerResource(route, "/" + route + API_URI)).collect(Collectors.toList());
    }

    private SwaggerResource swaggerResource(String name, String location) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("2.0");
        return swaggerResource;
    }
}
